import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCodeRain } from '@/scripts/components/CodeRain'

export interface NavItem {
  title: string
  img: string
  pageKey: string
}

export const useNavigationView = () => {
  const canvas = ref<HTMLCanvasElement | null>(null)
  const currentPage = ref(0) // 初始页面改为0
  const isScrolling = ref(false) 
  const router = useRouter()

  // 使用封装的代码雨效果
  const { initCanvas, handleResize, destroy } = useCodeRain(canvas, {
    letters: 'CodeForce',
    colors: ['#00BFFF', '#1E90FF', '#4169E1', '#4682B4', '#5F9EA0', '#20B2AA', '#008080', '#2E8B57'],
    fontSize: 10,
    animationSpeed: 60
  })

  const navItems: NavItem[] = [
    {
      title: 'tec', 
      img: '/img/coderain.png',
      pageKey: 'tec'
    },
    {
      title: '333',
      img: '/img/lives.JPG',
      pageKey: 'lives'
    }
  ]

  function handleWheel(event: WheelEvent) {
    if (isScrolling.value) return
    
    isScrolling.value = true
    
    if (event.deltaY > 0 && currentPage.value < 2) { // 最大页面改为2
      // 向下滚动
      currentPage.value++
    } else if (event.deltaY < 0 && currentPage.value > 0) { // 最小页面改为0
      // 向上滚动
      currentPage.value--
    }
    
    setTimeout(() => {
      isScrolling.value = false
    }, 800)
  }

  function scrollToPage(page: number) {
    if (isScrolling.value || page === currentPage.value) return
    
    isScrolling.value = true
    currentPage.value = page
    
    setTimeout(() => {
      isScrolling.value = false
    }, 800)
  }

  function navigateTo(pageKey: string) {
    router.push(`/${pageKey}`)
  }

  onMounted(() => {
    initCanvas()
    window.addEventListener('resize', handleResize)
    window.addEventListener('wheel', handleWheel, { passive: false })
  })

  onUnmounted(() => {
    destroy()
    window.removeEventListener('wheel', handleWheel)
  })

  return {
    canvas,
    currentPage,
    isScrolling,
    navItems,
    scrollToPage,
    navigateTo
  }
}